package we.core.handlers;

import java.nio.channels.SocketChannel;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import we.common.CCommonHandler;
import we.core.bean.CDataContainer;
import we.core.bean.CRoom;
import we.core.bean.CUser;
import we.extension.CSystemEvent;


public class CCreateRoomHandler extends CAbstractCoreHandler {
    public CCreateRoomHandler() {
    }

    @Override
    public int handleEvent(SocketChannel channel, JSONObject data) {        
        try {
            CUser owner;
            CDataContainer temp = CDataContainer.instance();
            CCommonHandler.trace(temp.getUsers().size());
            owner = (CUser)temp.getUser(data.getString("owner"));
            String rName = data.getString("rName");
            int maxUser = data.getInt("maxUser");
            String password = data.getString("password");
            CRoom r = new CRoom(owner.username, rName, maxUser, password);
            CDataContainer.instance().addRoom(r);
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("eventName", CSystemEvent.SystemEventType.CREATE_ROOM);
            params.put("owner", owner);
            params.put("room", r);
            CSystemEvent se = new CSystemEvent(this, params);
            dispatchSystemEvent(se);
            return r.getRoomId();
        } catch (JSONException e) {
            CCommonHandler.writeErrLog(e);
            return -1; // create room false
            // TODO
        }
    }
}
